package com.schedule.jobs;

import com.alibaba.fastjson.JSONObject;
import com.report.doc.BaseDoc;
import com.report.doc.ExcelService;
import com.report.doc.WordService;
import com.schedule.ReportGenerateScheduleManage;
import com.schedule.domain.Attachment;
import com.schedule.domain.ReportRule;
import com.schedule.domain.Template;
import com.util.MD5Util;
import com.util.exportout.IFileData;
import com.util.exportout.excel.Excel2003;
import lombok.extern.slf4j.Slf4j;
import org.quartz.Job;
import org.quartz.JobDataMap;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import com.report.repository.AttachmentRepository;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @Auther zhangdajun
 * @CreateDate 2018/11/3 09 56
 * @Describe
 */
@Slf4j
@Component
public class ReportJob implements Job {
//
//    @Autowired
//    StringRedisTemplate stringRedisTemplate;
//    @Autowired
//    SearchDataService searchDataService;
    @Autowired
    AttachmentRepository attachmentRepository;

//    @Value("${system.file.output}")
//    String reportPath;
//
//    @Value("${template.filePath}")
//    String templateth;

    /** 报表生成路径 */
    @Value("${report.path}")
    protected String reportPath;

    /** 报表模板路径前缀 */
    @Value("${report.template}")
    protected String reportTemplatePath;

    /** 报表模板路径前缀 */
    @Value("${report.default-sql}")
    protected String defaultSQL;

    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {

        JobDataMap data = jobExecutionContext.getJobDetail().getJobDataMap();

        Template template = JSONObject.parseObject(data.getString
                (ReportGenerateScheduleManage.PARAM_KEY_RULE), Template.class);

//        List<ReportRuleTask> reportRuleTasks = JSONArray.parseArray(data.getString(ReportGenerateScheduleManage.PARAM_KEY_RULE_TASK), ReportRuleTask.class);

        log.info("开始生成报告，报表规则:{},涉及任务:{},开始时间：",
                JSONObject.toJSONString(template), new Date());

        // 生成文件状态
        boolean createStatus = false;
        String filePath = null;
        try {
            // 报表模板路径
            template.setReportTemplatePath(reportTemplatePath);
            // 报表生成路径
            template.setReportPath(reportPath);
            // 默认SQL
            template.setDefaultSQL(defaultSQL);

            // 模板路径
            String templateFile = template.getPath();

            // 模板文件所在路径
            String templatePath = reportTemplatePath + File.separator + templateFile;

            // 设置模板文件的路径
            template.setPath(templatePath);

            // 判断文件类型
            int i = templateFile.lastIndexOf(".");
            String suffix = templateFile.substring(i + 1);
            BaseDoc doc = null;
            if(suffix.startsWith("docx")){
                doc = WordService.getInstance(template);
            } else if(suffix.startsWith("xlsx")){
                doc = ExcelService.getInstance(template);
            } else {
                String msg = "模板文件格式错误！模板文件：" + templateFile;
                log.info(msg);
                throw new Exception(msg);
            }


            //  初始化文件
            doc.init();
            // 生成文件
            doc.create();

            createStatus = true;
            log.info("文件{}生成完成！", filePath);
        } catch (Exception e) {
            System.out.println(e);
            log.info("{}",e);
            log.error("文件创建失败，文件信息：{}", JSONObject.toJSONString(template));
            createStatus = false;
            return;
        } finally {
            if (createStatus) {
                Attachment attachment = new Attachment();
//                attachment.setId(UUID.randomUUID().toString().substring(0,31));
                attachment.setId(MD5Util.getMD5((template.getName()).getBytes()));
                attachment.setPath(reportPath);
                attachment.setName(template.getName());
                attachment.setSuffix("xls");
                attachment.setDocCode(template.getDocCode());
                attachment.setCreateTime(new Date());
                attachment.setRuleId(template.getId());//报表表增加规则id
//                attachmentRepository.save(attachment);
            }
        }
    }

    public IFileData initFile(ReportRule reportRule) throws Exception {

        // 创建头部信息,生成文件名
        String fileName = formatFileName(reportRule.getReportTitleRule()).replace("(个性化)","(通用)");

        // 生成文件目录
        String tmp = reportPath + File.separator + reportRule.getId();

        IFileData file = new Excel2003();

        File dir = new File(tmp);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        file.setFileDir(tmp);
        file.init(fileName);

        String[] titles = {"taskName&任务名称", "resName&资源名称","ip&资源IP", "kpiName&指标名称", "subResourceId&指标子名称",
                "kpiValue&指标值", "status&是否正常", "executeTime&任务执行时间"};

        List<String> info = new ArrayList<String>();
        // merge 代表开始行、结束行、开始列、结束列
        info.add("[{\"merge\":\"[0,0,0,6]\",\"data\":\"" + fileName + "\",\"style\":\"titleStyleBase\"}]");
        info.add("[{\"merge\":\"[1,1,0,6]\",\"style\":\"subTitleStyleBase\",\"data\":\"报告生成时间:" + new SimpleDateFormat("yyyy年MM月dd日 HH时mm分ss秒").format(new Date()) + "\"}]");
        file.creatDataInfoByStr(info);

        file.creatDataHeadByListStr(Arrays.asList(titles));

        return file;
    }

    public String formatFileName(String name) {
        Date now = new Date();
        return name.replaceAll("\\{yyyy}", new SimpleDateFormat("yyyy").format(now))
                .replaceAll("\\{MM}", new SimpleDateFormat("MM").format(now))
                .replaceAll("\\{dd}", new SimpleDateFormat("dd").format(now))
                .replaceAll("\\{HH}", new SimpleDateFormat("HH").format(now))
                .replaceAll("\\{mm}", new SimpleDateFormat("mm").format(now))
                .replaceAll("\\{ss}", new SimpleDateFormat("ss").format(now))
                ;
    }
}
